package HibernateDAO;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import Hibernate.HibernateUtil;
import beans.Cliente;

public class HibernateClienteDAO {
	private static HibernateClienteDAO instancia;
	
	private static SessionFactory sf;

	public static HibernateClienteDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia=new HibernateClienteDAO();
		} 
		return instancia;
	}
	
	@SuppressWarnings("unchecked")
	public List<Cliente> obtenerTodosLosClientes(){
		Session session = sf.openSession();
		Query q = session.createQuery("from Cliente p");
		List<Cliente> listaDeClientes = new ArrayList<Cliente>(q.list());
		session.close();
		return listaDeClientes;
	}
	
	public void guardarUnCliente(Cliente cliente){
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(cliente); 
		session.getTransaction().commit();
		session.close();		
	}	
	
	public void borrarUnCliente(Cliente cliente){
		Session session = sf.openSession();
		session.beginTransaction();
		//session.createQuery("DELETE FROM beans.Lista l WHERE l.proveedor.id = :id").setLong("id", proveedor.getIdProveedor()).executeUpdate();
		session.delete(cliente); 
		session.getTransaction().commit();
		session.close();
	}
	
	public Cliente obtenerCliente(String razonSocial){
		// Obtenemos proveedor por 'razonSocial'
		Session session = sf.openSession();
		Query q = session.createQuery("FROM Cliente c WHERE c.RazonSocial = :razonSocial").setString("razonSocial", razonSocial);
		Cliente prov = (Cliente) q.uniqueResult();
		session.close();
		return prov;
	}
}